package org.example.elastic.lite.handler;

import com.dangdang.ddframe.job.config.JobCoreConfiguration;
import com.dangdang.ddframe.job.config.simple.SimpleJobConfiguration;
import com.dangdang.ddframe.job.event.JobEventConfiguration;
import com.dangdang.ddframe.job.lite.api.strategy.impl.AverageAllocationJobShardingStrategy;
import com.dangdang.ddframe.job.lite.config.LiteJobConfiguration;
import com.dangdang.ddframe.job.lite.internal.schedule.JobRegistry;
import com.dangdang.ddframe.job.lite.spring.api.SpringJobScheduler;
import com.dangdang.ddframe.job.reg.zookeeper.ZookeeperRegistryCenter;
import lombok.extern.slf4j.Slf4j;
import org.example.elastic.lite.config.DynamicElasticJobListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 动态定时任务相关操作工具类
 * @author 魏荣杰
 * @date 2022/11/11 10:02
 * @since
 * @version
 */
@Slf4j
@Component
public class DynamicElasticJobHandler {

    @Resource
    private ZookeeperRegistryCenter zookeeperRegistryCenter;
    @Resource
    private DynamicElasticJobListener dynamicElasticJobListener;
    @Resource
    private JobEventConfiguration jobEventConfiguration;


    public void addSimpleJob(String jobName, String cron, int shardingTotalCount, com.dangdang.ddframe.job.api.simple.SimpleJob simpleJob, String parameters, String descrption) {
        log.info("add job, jobName: {}, cron: {}, shardingTotalCount: {}, parameters: {}, descrption: {}", jobName, cron, shardingTotalCount, parameters, descrption);

        // 定义作业核心配置
        JobCoreConfiguration jobCoreConfiguration = JobCoreConfiguration.newBuilder(jobName, cron, shardingTotalCount)
                .jobParameter(parameters)
                .description(descrption)
                .build();

        // 定义SIMPLE类型配置
        SimpleJobConfiguration simpleJobConfiguration = new SimpleJobConfiguration(jobCoreConfiguration, simpleJob.getClass().getName());

        // 作业分片策略
        // 基于平均分配算法的分片策略
        String jobShardingStrategyClass = AverageAllocationJobShardingStrategy.class.getCanonicalName();

        // 定义Lite作业根配置
        LiteJobConfiguration.Builder builder = LiteJobConfiguration.newBuilder(simpleJobConfiguration)
                .jobShardingStrategyClass(jobShardingStrategyClass)
                .overwrite(true);

        LiteJobConfiguration liteJobConfiguration = builder.build();

        new SpringJobScheduler(simpleJob, zookeeperRegistryCenter, liteJobConfiguration, jobEventConfiguration, dynamicElasticJobListener).init();

    }

    public void updateJob(String jobName, String cron) {
        log.info("update job, jobName: {}, cron: {}", jobName, cron);
        JobRegistry.getInstance().getJobScheduleController(jobName).rescheduleJob(cron);
    }

    public void removeJob(String jobName) {
        log.info("remove job, jobName: {}", jobName);
        JobRegistry.getInstance().getJobScheduleController(jobName).shutdown();
    }
}
